﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Imaging;
using System.Drawing;

namespace yaip.Filters.PixelPoint {
    public class GrayScale : PixelPointFilter {


        public bool apply(System.Drawing.Bitmap image) {
            int height = image.Height;
            int width = image.Width;
            BitmapData bmData = image.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, image.PixelFormat);

            // How wide a line is
            int stride = bmData.Stride;
            // Pointer to the data  
            System.IntPtr Scan0 = bmData.Scan0;

            //because of the pointers (compiling flag: /unsafe)
            unsafe {
                byte* ptr = (byte*)(void*)Scan0;

                // We need the offset to skip the existent padding
                // in each row (bitmaps are word align)
                int nOffset = stride - width * 3;
                byte red, green, blue;

                for (int y = 0; y < height; ++y) {
                    for (int x = 0; x < width; ++x) {
                        blue = ptr[0];
                        green = ptr[1];
                        red = ptr[2];

                        ptr[0] = ptr[1] = ptr[2] = (byte)(.299 * red + .587 * green + .114 * blue);

                        ptr += 3;
                    }
                    ptr += nOffset;
                }
            }
            image.UnlockBits(bmData);
            return true;
        }
    }
}

